<template>
  <div id="container">
    <div ref="mapContainer" class="map-container"></div>
    <div class="search">
      <div>请输入关键字</div>
      <input id="tipinput" placeholder="请输入" />
    </div>
  </div>
  <div id="app">
    <div id="sidebar" v-show="isSidebarVisible" @mouseleave="hideSidebar">
        <TerminalList></TerminalList>
    </div>
  </div>
  <div>
    <TerminalDrawer @register="register" />
  </div>

</template>
<script>
import { provide,ref, onMounted, onUnmounted,defineComponent } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Alert } from 'ant-design-vue';
import { useDrawer } from '/@/components/Drawer';
import TerminalDrawer from "./TerminalDrawer.vue";
import TerminalList from './TerminalList.vue';
import {defHttp} from '/@/utils/http/axios';
import terminalImg from '/@/assets/jufang/terminal.png';
window._AMapSecurityConfig = {
  securityJsCode: '0211acb3aa72a596f0f9844599450768'
}
export default defineComponent({
  components: {TerminalDrawer, AMapLoader,TerminalList },
   setup() {
    const [register, {openDrawer,closeDrawer}] = useDrawer();
    const APP_addMapMarker = ref(() => {});
    const setMapCenter = ref(() =>{});
    /**坐标全局变量*/
    const APP_coordinate = ref("0,0");
    /**将鼠标点击的坐标提供给子类使用*/
    provide('APP_coordinate', APP_coordinate);
    let map = null;

    // 设置一个图标对象
     const icon = {
       // 图标类型，现阶段只支持 image 类型
       type: 'image',
       // 图片 url
       image: terminalImg,
       // 图片尺寸
       size: [64, 30],
       // 图片相对 position 的锚点，默认为 bottom-center
       anchor: 'center',
     };
     const textStyle = {
       fontSize: 12,
       fontWeight: 'normal',
       fillColor: '#22886f',
       strokeColor: '#fff',
       strokeWidth: 2,
       fold: true,
       padding: '2, 5',
     };

     onMounted(() => {
      AMapLoader.load({
        key: "d092e9075ca5c956f52bdf07d73050c6", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then(async (AMap) => {
        let params = {mark: 'isNotNull'}
        const terminalList = await defHttp.get({url: '/yc/web/terminal/listCoordinateIsNull', params});
        let center = [116.469881, 39.993599];
        if(terminalList.records.length > 0){
          center = terminalList.records[0].coordinate.split(",");
        }
        const allowCollision = true;
        const layer = new AMap.LabelsLayer({
          zooms: [3, 20],
          zIndex: 1000,
          // collision: false,
          // 设置 allowCollision：true，可以让标注避让用户的标注
          allowCollision,
        });
        map = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "2D", // 是否为3D地图模式
          zoom: 15.8, // 初始化地图级别
          center, // 初始化地图中心点位置
          showIndoorMap: false,

        });
        setMapCenter.value = (coordinate) => {
          if(coordinate === null){
            return;
          }
          const Lng_lat = coordinate.split(",");
          map.setCenter(Lng_lat);
          map.setZoom(15.8)
        }
   /*     map.on('click', function (e) {
          //alert(e.lnglat.getLng() + ',' + e.lnglat.getLat())
        });*/
        const contextMenu = new AMap.ContextMenu();
        map.on('click', function (e) {
          APP_coordinate.value = e.lnglat.getLng() + "," + e.lnglat.getLat();
          contextMenu.open(map, e.lnglat);
        });

       /* var markers = [];

        layer.add(markers);*/
        // 图层添加到地图
        map.add(layer);
        // 初始化 labelMarker
       /* for (var i = 0; i < LabelsData.length; i++) {
          var curData = LabelsData[i];
          curData.extData = {
            index: i,
          };

          var labelMarker = new AMap.LabelMarker(curData);

          markers.push(labelMarker);
        }*/
        const LabelsData = [];
        terminalList.records.forEach(function(item, index) {
          const id = item.id;
          const curData = {
            id: item.id,
            name: item.name,
            position: item.coordinate.split(","),
            zooms: [10, 20],
            opacity: 1,
            zIndex: 10,
            fold: true,
            icon,
            text: {
              // 要展示的文字内容
              content: item.name,
              // 文字方向，有 icon 时为围绕文字的方向，没有 icon 时，则为相对 position 的位置
              direction: 'right',
              // 在 direction 基础上的偏移量
              offset: [-20, -5],
              // 文字样式
              style: {
                // 字体大小
                fontSize: 12,
                // 字体颜色
                fillColor: '#22886f',
                //
                strokeColor: '#fff',
                strokeWidth: 2,
                fold: true,
                padding: '2, 5',
              },
            },
            extData: {
              index: index,
            },
          };
          const labelMarker = new AMap.LabelMarker(curData);
          const MarkerMenu = new AMap.ContextMenu();
          MarkerMenu.addItem("删除设备", function (e) {
            layer.remove(labelMarker);
            let params = {id:id}
            defHttp.post({url: '/yc/web/terminal/editCoordinateNULL?id='+id, params});
            MarkerMenu.close();
          }, 0);
          labelMarker.on('click', function (e) {
            MarkerMenu.open(map, e.lnglat);
          });
          /*markers.push(labelMarker);*/
          layer.add(labelMarker);
        });
     /*   for(let i = 0; i < terminalList.records.length; i++){

        }*/
        // 将 marker 添加到图层

        map.setFitView(null, false, [100, 150, 10, 10]);
        //右键放大
        contextMenu.addItem("放大一级", function () {
          map.zoomIn();
        }, 0);
        //右键缩小
        contextMenu.addItem("缩小一级", function () {
          map.zoomOut();
        }, 1);
        contextMenu.addItem("增加设备", function () {
          openDrawer(true, "1");
          contextMenu.close();
        }, 2);
        APP_addMapMarker.value = (terminalRecord) => {
          const id = terminalRecord.id;
          const coordinate = terminalRecord.coordinate.split(",");
          const labelMarker = new AMap.LabelMarker({
            id: terminalRecord.id,
            name: terminalRecord.name,
            position: coordinate,
            zooms: [10, 20],
            opacity: 1,
            zIndex: 16,
            icon,
            text: {
              content: terminalRecord.name,
              direction: 'right',
              offset: [-20, -5],
              style: textStyle,
            },
            extData: {
              index: 1,
            },
          });
          //markers.push(labelMarker);
          const MarkerMenu = new AMap.ContextMenu();
          labelMarker.on('click', function (e) {
            MarkerMenu.addItem("删除设备", function (e) {
              layer.remove(labelMarker);
              let params = {id:id}
              defHttp.post({url: '/yc/web/terminal/editCoordinateNULL?id='+id, params});
              MarkerMenu.close()
            }, 0);
            MarkerMenu.open(map, e.lnglat);
          });
          layer.add(labelMarker);
          closeDrawer();
        };
        // 搜索
        var autoOptions = {
          input: 'tipinput'
        }
        AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function () {
          var auto = new AMap.AutoComplete(autoOptions)
          var placeSearch = new AMap.PlaceSearch({
            map: map
          })
          // 构造地点查询类
          auto.on('select', select) // 注册监听，当选中某条记录时会触发
          function select(e) {
            placeSearch.setCity(e.poi.adcode)
            placeSearch.search(e.poi.name) // 关键字查询查询
          }
        }).catch((e) => {
          console.log(e)
        })
      })
        .catch((e) => {
          console.log(e);
        });
    });
    onUnmounted(() => {
      map?.destroy();
    });
    const isSidebarVisible = ref(false); // 侧边栏是否可见
    const sidebar = ref(null); // 侧边栏 DOM 引用

    // 显示侧边栏的方法
    const showSidebar = () => {
      isSidebarVisible.value = true;
    };

    // 隐藏侧边栏的方法
    const hideSidebar = () => {
      isSidebarVisible.value = false;
    };

    // 监听鼠标移动事件的方法
    const handleMouseMove = (event) => {
      const windowWidth = window.innerWidth;
      const triggerWidth = 20; // 设置一个距离屏幕最右边 triggerWidth px 的触发区域
      if (event.clientX >= windowWidth - triggerWidth) {
        showSidebar();
      } else if (isSidebarVisible.value && event.clientX < (windowWidth * 0.6)) {
        hideSidebar();
      }
    };

    // 在组件挂载时添加事件监听器
    onMounted(() => {
      window.addEventListener('mousemove', handleMouseMove);
    });

    // 在组件卸载时移除事件监听器
    onUnmounted(() => {
      window.removeEventListener('mousemove', handleMouseMove);
    });
    const parentMethod = (terminalRecord) => {

      console.log('父组件方法被调用');
      console.log(JSON.stringify(terminalRecord))

    };

    provide('APP_setMapCenter', setMapCenter);
    // 使用 provide 将方法提供给子组件
    provide('APP_addMapMarker', APP_addMapMarker);

    return {
      isSidebarVisible,
      sidebar,
      hideSidebar,
      register,
      openDrawer,
      closeDrawer,
    };

  },

});
</script>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
html, body, #container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#sidebar {
  position: fixed;
  right: 0px; /* 初始时将侧边栏放在屏幕外面 */
  top: 0;
  width: 40%;
  height: 70%;
  background-color: #333;
  color: #fff;
  padding: 10px;
  transition: right 0.3s ease; /* 添加过渡效果 */
  z-index: 9999; /* 设置层级最高 */
  overflow-y: auto; /* 允许侧边栏内容滚动 */
}
#sidebar.visible {
  right: 0; /* 显示侧边栏时将其移动到屏幕最右边 */
}
.container {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 9;
}
.map-container {
  width: 100%;
  height: 100%;
}
.search {
  position: absolute;
  top: 2%;
  left: 2%;
  z-index: 99;
}
</style>
